package com.niit.onlinemusicserver.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

@Component
public class EmailLinkUtil {

    @Autowired
    private MailProperties mailProperties;


    public void sendActivationEmail(String recipientEmail, String activationCode) throws MessagingException {

        // 创建session
        Session session = Session.getInstance(new Properties());
        // 通过session得到transport对象
        Transport ts = session.getTransport();
        // 连接邮件服务器：邮箱类型，帐号，授权码代替密码（更安全）
        ts.connect(mailProperties.getHost(), mailProperties.getUsername(), mailProperties.getPassword());
        //声明一个Message对象(代表一封邮件),从session中创建
        MimeMessage msg = new MimeMessage(session);
        //邮件信息封装
        //1发件人
        msg.setFrom(new InternetAddress(mailProperties.getUsername()));
        //2收件人
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
        //3邮件内容:主题、内容
        msg.setSubject("Online Music 邮箱登录验证码");

        //添加附件部分
        //邮件内容部分1---文本内容
        //邮件中的文字部分
        MimeBodyPart body = new MimeBodyPart();
        body.setContent("<h1>" + activationCode + "</h1>", "text/html");
        //把上面的2部分组装在一起，设置到msg中
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(body);
        msg.setContent(mm);
        // 发送邮件
        ts.sendMessage(msg, msg.getAllRecipients());
        ts.close();
    }

}
